package dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Phone4 {
    public static void main(String[] args) {
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db= null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //解析XML文档,得到一个Document对象,即DOM树
        Document doc = null;
        try {
            doc = db.parse("src/xml/Phone.xml");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建Brand节点
        Element brandElement=doc.createElement("Brand");
        brandElement.setAttribute("name","三星");
        //创建Type节点
        Element typeElement=doc.createElement("Type");
        typeElement.setAttribute("name","Notex");
        //添加父子关系
        brandElement.appendChild(typeElement);
        Element phoneElement=(Element)doc.getElementsByTagName("PhoneInfo").item(0);
        //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer= null;
        try {
            transformer = transformerFactory.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
        DOMSource domSource=new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
        StreamResult result= null;
        try {
            result = new StreamResult(new FileOutputStream("src/xml/Phone.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //吧DOM树转换为XML文件
        try {
            transformer.transform(domSource,result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
